import express from 'express'
import { authMiddleware } from '../middleware/auth'
import { RoomService } from '../services/room/RoomService'
import { errorResponse, successResponse } from '../utils/responseHandler'

const router = express.Router()
const roomService = new RoomService()

// 获取房间列表
router.get('/', async (_req: express.Request, res: express.Response) => {
  try {
    const rooms = await roomService.listRooms()
    return successResponse(res, rooms)
  } catch (error) {
    return errorResponse(res, 500, 'Failed to fetch rooms')
  }
})

// 创建新房间
router.post('/', authMiddleware, async (req: express.Request, res: express.Response) => {
  try {
    const { name } = req.body
    const userId = (req as any).user.userId

    if (!name) {
      return errorResponse(res, 400, 'Room name is required')
    }

    const room = await roomService.createRoom(userId, name)
    return successResponse(res, room, 'Room created successfully')
  } catch (error) {
    return errorResponse(res, 500, 'Failed to create room')
  }
})

// 获取特定房间信息
router.get('/:roomId', async (req: express.Request, res: express.Response) => {
  try {
    const { roomId } = req.params
    const room = await roomService.getRoomById(roomId)
    return successResponse(res, room)
  } catch (error) {
    if (error instanceof Error) {
      return errorResponse(res, 404, error.message)
    }
    return errorResponse(res, 500, 'Failed to fetch room')
  }
})

export default router
